package models

import (
	"errors"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

type Active struct {
	Id          int       `orm:"column(Id)"`
	Title       string    `orm:"column(Title)"`
	CreateTime  time.Time `orm:"column(CreateTime)"`
	StartTime   time.Time `orm:"column(StartTime)"`
	EndTime     time.Time `orm:"column(EndTime)"`
	Describtion string    `orm:"column(Describtion)"`
	Address     string    `orm:"column(Addr)"`
	Status      int       `orm:"column(Status)"` //1：删除
	Content     string    `orm:"column(Content)"`
	ActiveImg   string    `orm:"column(ActiveImg)"`
	Location    string    `orm:"column(Location)"`
	NickName    string    `orm:"column(NickName)"`
	WeChatId    string    `orm:"column(WeChatId)"`
	Creater     *User     `orm:"null;rel(one);on_delete(set_null)"`
}

func (p *Active) Insert() (int64, error) {
	o := orm.NewOrm()
	o.Using("default")

	return o.Insert(&p)
}

func InsertActive(user *User, active *Active) (int64, error) {

	o := orm.NewOrm()
	o.Using("default")

	active.Creater = user

	return o.Insert(active)
}

func DeleteActive(Id int, user *User) error {
	o := orm.NewOrm()
	o.Using("default")

	_, err := o.QueryTable(Active{}).Filter("Id", Id).Filter("Creater", user.Id).Update(orm.Params{
		"Status": 1,
	})

	return err
}

func (a *Active) TableName() string {
	return "Active"
}

type ActiveJoinedUser struct {
	Id         int       `orm:"column(Id)"`
	NickName   string    `orm:"column(NickName)"`
	HeadImg    string    `orm:"column(HeadImg)"`
	ActiveId   int       `orm:"column(ActiveId)"`
	Realname   string    `orm:"column(RealName)"`
	Tel        string    `orm:"column(Telephone)"`
	Department string    `orm:"column(DepartMent)"`
	Createtime time.Time `orm:"column(CreateTime)"`
	User       *User     `orm:"rel(fk);column(UserId)"`
}

func (a *ActiveJoinedUser) TableName() string {
	return "ActiveJoinUser"
}

func AddUserToActive(user *User, name, tel, department string, activeId int) error {

	o := orm.NewOrm()
	o.Using("default")

	newJoin := ActiveJoinedUser{
		User:       user,
		ActiveId:   activeId,
		Realname:   name,
		Department: department,
		Tel:        tel,
		NickName:   user.NickName,
		HeadImg:    user.HeadImg,
		Createtime: time.Now(),
	}

	oldJoin := ActiveJoinedUser{
		User:     user,
		ActiveId: activeId,
	}
	err := o.Read(&oldJoin, "User", "ActiveId")
	if err != nil {
		beego.Error("get old join failde:", err)
	}

	if oldJoin.Id > 0 {
		beego.Error("have joined active")
		return errors.New("已经报名，不需要重复报名")
	}

	_, err = o.Insert(&newJoin)
	if nil != err {
		beego.Error("insert to db failed:", err)
	}
	return err

}

type detail struct {
	Icon    string `json:"headUrl"`
	JoinNum int    `json:"joinNum"`
}

type ActiveWithJoin struct {
	Id          int    `json:"Id"`
	Title       string `json:"Title"`
	CreateTime  string `json:"CreateTime"`
	StartTime   string `json:"StartTime"`
	EndTime     string `json:"EndTime"`
	Describtion string `json:"Describtion"`
	Address     string `json:"Addr"`
	Content     string `json:"Production"`
	ActiveImg   string `json:"ActiveImg"`
	Location    string `json:"Location"`
	Join        bool   `json:"Join"`
	Creater     bool   `json:"Creater"`
	Status      string `json:"Status"`
	Detail      detail `json:detail`
}

//查询用户参与的活动
func QueryJoindActives(user *User) (orm.ParamsList, error) {

	var list orm.ParamsList

	o := orm.NewOrm()
	active := new(ActiveJoinedUser)
	_, err := o.QueryTable(active).Filter("UserId", user.Id).ValuesFlat(&list, "ActiveId")
	if err != nil {
		beego.Error("acs active failed!", err)
		return list, err
	}

	return list, nil
}

func QueryActivesWithJoin(user *User, location string) ([]ActiveWithJoin, error) {

	o := orm.NewOrm()

	list, err := QueryJoindActives(user)
	if err != nil {
		beego.Error("acs joined active failed!", err)
	}

	var result []ActiveWithJoin
	for _, joined := range list {

		v := Active{
			Id: int(joined.(int64)),
		}
		err := o.Read(&v)
		if err != nil {
			beego.Error("querry failed!", err, joined)
			continue
		}

		newActive := ActiveWithJoin{
			Id:          v.Id,
			Title:       v.Title,
			CreateTime:  v.CreateTime.Format("1月2日 15:04"),
			StartTime:   v.StartTime.Format("1月2日 15:04"),
			EndTime:     v.EndTime.Format("1月2日 15:04"),
			Describtion: v.Describtion,
			Address:     v.Address,
			Content:     staffRoleConvert(v.Content),
			ActiveImg:   v.ActiveImg,
			Join:        true,
			Creater:     true,
		}

		now := time.Now()
		if now.After(v.EndTime) {
			newActive.Status = "已结束"
		} else if now.After(v.StartTime) && now.Before(v.EndTime) {
			newActive.Status = "进行中"
		} else {
			newActive.Status = "即将开始"
		}

		result = append(result, newActive)

	}

	return result, nil
}

func QueryActivesWithCreate(user *User, location string) ([]ActiveWithJoin, error) {
	var actives []*Active

	o := orm.NewOrm()

	active := new(Active)
	acs := o.QueryTable(active)

	_, err := acs.OrderBy("-CreateTime").Filter("Creater", user.Id).Limit(10).All(&actives)
	if err != nil {
		beego.Error("acs active failed!", err)
		return nil, err
	}

	now := time.Now()
	var result []ActiveWithJoin
	for _, v := range actives {

		cnt, err := o.QueryTable(ActiveJoinedUser{}).Filter("ActiveId", v.Id).Count()
		if err != nil {
			beego.Error("acs active failed!", err)
			return nil, err
		}

		rtdetail := detail{
			JoinNum: int(cnt),
			Icon:    v.Creater.HeadImg,
		}

		newActive := ActiveWithJoin{
			Id:          v.Id,
			Title:       v.Title,
			CreateTime:  v.CreateTime.Format("1月2日 15:04"),
			StartTime:   v.StartTime.Format("1月2日 15:04"),
			EndTime:     v.EndTime.Format("1月2日 15:04"),
			Describtion: v.Describtion,
			Address:     v.Address,
			Content:     staffRoleConvert(v.Content),
			ActiveImg:   v.ActiveImg,
			Join:        true,
			Creater:     true,
			Detail:      rtdetail,
		}

		if now.After(v.EndTime) {
			newActive.Status = "已结束"
		} else if now.After(v.StartTime) && now.Before(v.EndTime) {
			newActive.Status = "进行中"
		} else {
			newActive.Status = "即将开始"
		}

		result = append(result, newActive)
	}

	return result, nil
}

func QueryActivesDetail(user *User, location string, activeId int) (*ActiveWithJoin, error) {

	actives := Active{
		Id: activeId,
	}
	o := orm.NewOrm()

	err := o.Read(&actives)
	if err != nil {
		beego.Error("acs active failed!", err)
		return nil, err
	}

	cnt, err := o.QueryTable(ActiveJoinedUser{}).Filter("ActiveId", activeId).Count()
	if err != nil {
		beego.Error("acs active failed!", err)
		return nil, err
	}

	rtdetail := detail{
		JoinNum: int(cnt),
		Icon:    actives.Creater.HeadImg,
	}

	res := ActiveWithJoin{
		Id:          actives.Id,
		Title:       actives.Title,
		CreateTime:  actives.CreateTime.Format("1月2日 15:04"),
		StartTime:   actives.StartTime.Format("1月2日 15:04"),
		EndTime:     actives.EndTime.Format("1月2日 15:04"),
		Describtion: actives.Describtion,
		Address:     actives.Address,
		Content:     staffRoleConvert(actives.Content),
		ActiveImg:   actives.ActiveImg,
	}
	res.Detail = rtdetail

	now := time.Now()
	if now.After(actives.EndTime) {
		res.Status = "已结束"
	} else if now.After(actives.StartTime) && now.Before(actives.EndTime) {
		res.Status = "进行中"
	} else {
		res.Status = "即将开始"
	}

	if actives.Creater.Id == user.Id {
		res.Creater = true
	}

	//查询用户所参加的活动
	list, err := QueryJoindActives(user)
	if err != nil {
		beego.Error("acs joined active failed!", err)
	}

	for _, joined := range list {
		if int(joined.(int64)) == actives.Id {
			res.Join = true
		}
	}

	return &res, nil
}

func QueryActives(user *User, location string) ([]ActiveWithJoin, error) {

	var actives []*Active

	o := orm.NewOrm()

	active := new(Active)
	acs := o.QueryTable(active)

	_, err := acs.OrderBy("-CreateTime").Filter("Status", "active").Limit(10).All(&actives)
	if err != nil {
		beego.Error("acs active failed!", err)
		return nil, err
	}

	//查询用户所参加的活动
	list, err := QueryJoindActives(user)
	if err != nil {
		beego.Error("acs joined active failed!", err)
	}

	beego.Debug("list", list)

	now := time.Now()
	var result []ActiveWithJoin
	for _, v := range actives {

		newActive := ActiveWithJoin{
			Id:          v.Id,
			Title:       v.Title,
			CreateTime:  v.CreateTime.Format("1月2日 15:04"),
			StartTime:   v.StartTime.Format("1月2日 15:04"),
			EndTime:     v.EndTime.Format("1月2日 15:04"),
			Describtion: v.Describtion,
			Address:     v.Address,
			Content:     staffRoleConvert(v.Content),
			ActiveImg:   v.ActiveImg,
			Join:        false,
		}

		if now.After(v.EndTime) {
			newActive.Status = "已结束"
		} else if now.After(v.StartTime) && now.Before(v.EndTime) {
			newActive.Status = "进行中"
		} else {
			newActive.Status = "即将开始"
		}

		if v.Creater.Id == user.Id {
			newActive.Creater = true
		}

		for _, joined := range list {
			if int(joined.(int64)) == v.Id {
				newActive.Join = true
			}
		}

		result = append(result, newActive)
	}

	return result, nil
}

func QueryCustormerByActive(activeId string) (int64, []orm.Params, error) {

	var list []orm.Params

	o := orm.NewOrm()
	o.Using("default")

	custormer := new(ActiveJoinedUser)
	number, err := o.QueryTable(custormer).Filter("ActiveId", activeId).Values(&list)
	if err != nil {
		beego.Error("acs custormer failed!", err)
		return 0, list, err
	}

	return number, list, nil
}
